#!/usr/bin/env node

const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');

console.log('🚀 正在启动 Chrome 笔记插件后端服务...');

// 检查当前目录
const currentDir = process.cwd();
console.log('当前目录:', currentDir);

// 检查必要文件
const requiredFiles = ['package.json', 'server.js'];
for (const file of requiredFiles) {
  const filePath = path.join(currentDir, file);
  if (!fs.existsSync(filePath)) {
    console.error(`❌ 缺少必要文件: ${file}`);
    process.exit(1);
  }
}

// 检查 node_modules
const nodeModulesPath = path.join(currentDir, 'node_modules');
if (!fs.existsSync(nodeModulesPath)) {
  console.log('📦 正在安装依赖...');
  const installProcess = spawn('npm', ['install'], {
    cwd: currentDir,
    stdio: 'inherit'
  });
  
  installProcess.on('close', (code) => {
    if (code === 0) {
      console.log('✅ 依赖安装完成');
      startServer();
    } else {
      console.error('❌ 依赖安装失败');
      process.exit(1);
    }
  });
} else {
  startServer();
}

function startServer() {
  console.log('🔧 正在启动服务器...');
  
  const serverProcess = spawn('node', ['server.js'], {
    cwd: currentDir,
    stdio: 'inherit'
  });
  
  serverProcess.on('error', (error) => {
    console.error('❌ 启动服务器时出错:', error.message);
    process.exit(1);
  });
  
  serverProcess.on('close', (code) => {
    if (code === 0) {
      console.log('✅ 服务器正常关闭');
    } else {
      console.error(`❌ 服务器异常退出，退出码: ${code}`);
    }
  });
  
  // 处理进程信号
  process.on('SIGINT', () => {
    console.log('\n🛑 正在关闭服务器...');
    serverProcess.kill('SIGINT');
  });
  
  process.on('SIGTERM', () => {
    console.log('\n🛑 正在关闭服务器...');
    serverProcess.kill('SIGTERM');
  });
} 